package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.provider.dao.OldmanMapper;
import com.csun.cmny.provider.dao.OmcOldManSupplementMapper;
import com.csun.cmny.provider.dao.OmcServiceOrderMapper;
import com.csun.cmny.provider.dto.OldmanQueryDto;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.constant.OldInConstant;
import com.csun.cmny.provider.model.domain.OmcAppUserOldmanBind;
import com.csun.cmny.provider.model.domain.OmcLevelCare;
import com.csun.cmny.provider.model.domain.OmcNursingLog;
import com.csun.cmny.provider.model.domain.OmcOldManSupplement;
import com.csun.cmny.provider.model.dto.*;
import com.csun.cmny.provider.model.dto.customerArchives.OldmanArchivesQueryDto;
import com.csun.cmny.provider.model.dto.message.OldmanInQueryDto;
import com.csun.cmny.provider.model.dto.oldmanApp.AppOldmanDto;
import com.csun.cmny.provider.model.dto.watch.OldmanBindWatchReqDto;
import com.csun.cmny.provider.model.vo.*;
import com.csun.cmny.provider.model.vo.customerArchives.OldmanArchivesListVo;
import com.csun.cmny.provider.model.vo.message.OldmanInVo;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.provider.utils.IdentityUtil;
import com.csun.cmny.provider.vo.*;
import com.csun.cmny.util.PublicUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("OldmanService")
@Transactional
public class OldmanServiceImpl implements OldmanService {

    @Resource
    private DmcRpcService dmcRpcService;
    @Resource
    OldmanMapper oldmanMapper;
    @Resource
    OmcOldManSupplementMapper omcOldManSupplementMapper;
    @Resource
    private OmcOldManSupplementService omcOldManSupplementService;
    @Resource
    private OmcAppUserOldmanBindService omcAppUserOldmanBindService;
    @Resource
    private UacRpcService uacRpcService;
    @Resource
    private OmcNursingLogService nursingLogService;
    @Resource
    private OmcMedicRecordService omcMedicRecordService;
    @Resource
    private OmcLevelCareService levelCareService;
    @Resource
    private OmcServiceOrderMapper omcServiceOrderMapper;

    @Override
    public Oldman selectByOld(Oldman oldman) {
        return oldmanMapper.selectByOld(oldman);
    }

    @Override
    public int insert(Oldman oldman) {
        return oldmanMapper.insert(oldman);
    }

    @Override
    public int insertSelective(Oldman oldman) {
        return oldmanMapper.insertSelective(oldman);
    }

    @Override
    public int deleteByOldId(Integer oldmanId) {
        return oldmanMapper.deleteByPrimaryKey(oldmanId);
    }

    @Override
    public int updateByOldId(Oldman oldman) {
        return oldmanMapper.updateByPrimaryKeySelective(oldman);
    }

    @Override
    public List<Map<String, Object>> showAll(Map<String, Object> queryMap) {
        return oldmanMapper.showAll(queryMap);
    }

    @Override
    public List<Map<String, Object>> showIn(Map<String, Object> queryMap) {
        return oldmanMapper.showIn(queryMap);
    }

    @Override
    public Oldman checkOldmanbelong(OldmanRpcDto oldmanRpcDto) {
        return oldmanMapper.checkOldmanbelong(oldmanRpcDto);
    }

    /**
     * query oldman address
     *
     * @param oldmanAddressQueryDto oldman address query dto
     *
     * @return the list.
     */
    @Override
    public List<OldmanAddressVo> queryOldmanAddress(OldmanAddressQueryDto oldmanAddressQueryDto) {

        List<OldmanAddressVo> oldmanAddressVoList = oldmanMapper.queryOldmanAddress(oldmanAddressQueryDto);
        if (PublicUtil.isEmpty(oldmanAddressVoList)) {
            return null;
        }

        List<Integer> oldmanIds = oldmanAddressVoList.stream().map(o -> o.getOldmanId()).collect(Collectors.toList());

        // 获取老人手环地址
        List<WatchOldmanAddressVo> watchOldmanAddressVoList = dmcRpcService.queryWatchOldmanAddressByOldmanIds(oldmanIds);
        Map<Integer, WatchOldmanAddressVo> watchOldmanAddressVoMap =
                watchOldmanAddressVoList.stream().collect(Collectors.toMap(WatchOldmanAddressVo::getOldmanId, a -> a,(k1, k2)->k1));

        for (OldmanAddressVo oldmanAddressVo : oldmanAddressVoList) {
            WatchOldmanAddressVo watchOldmanAddressVo = watchOldmanAddressVoMap.get(oldmanAddressVo.getOldmanId());
            if (PublicUtil.isNotEmpty(watchOldmanAddressVo)) {
                oldmanAddressVo.setBind(true);
                oldmanAddressVo.setWatchOldmanAddressVo(watchOldmanAddressVo);
            }
        }

        return oldmanAddressVoList;
    }

    /**
     * query oldman not bind watch list
     *
     * @param oldmanNotBindWatchQueryDto oldman not bind watch query dto
     * @return the list
     */
    @Override
    public PageInfo queryOldmanNotBindWatchList(OldmanNotBindWatchQueryDto oldmanNotBindWatchQueryDto) {

        OldmanBindWatchReqDto oldmanBindWatchReqDto = new OldmanBindWatchReqDto();
        oldmanBindWatchReqDto.setGroupId(oldmanNotBindWatchQueryDto.getGroupId());
        List<Integer> oldmanIdList = dmcRpcService.queryOldmanBindWatchList(oldmanBindWatchReqDto);

        oldmanNotBindWatchQueryDto.setOldmanIdList(oldmanIdList);
        PageHelper.startPage(oldmanNotBindWatchQueryDto.getPageNum(), oldmanNotBindWatchQueryDto.getPageSize());
        List<OldmanNotBindWatchVo> oldmanNotBindWatchVoList =
                oldmanMapper.queryOldmanNotBindWatchList(oldmanNotBindWatchQueryDto);

        return new PageInfo<>(oldmanNotBindWatchVoList);
    }

    /**
     * query oldman bed room building list all
     *
     * @param oldmanIdList oldman id list
     *
     * @return the list.
     */
    @Override
    public List<OldmanBedRoomBuildingVo> queryOldmanBedRoomBuildingList(List<Integer> oldmanIdList) {

        return oldmanMapper.queryOldmanBedRoomBuildingList(oldmanIdList);
    }

    /**
     * query bed room building oldman list
     *
     * @param bedIdList bed id list
     *
     * @return the list.
     */
    @Override
    public List<OldmanBedRoomBuildingVo> queryBedRoomBuildingOldmanList(List<Integer> bedIdList) {

        return oldmanMapper.queryBedRoomBuildingOldmanList(bedIdList);
    }

    /**
     * query bed room building oldman list by room id
     *
     * @param roomId room id
     *
     * @return the list.
     */
    @Override
    public List<OldmanBedRoomBuildingVo> queryBedRoomBuildingOldmanListByRoomId(Integer roomId) {

        return oldmanMapper.queryBedRoomBuildingOldmanListByRoomId(roomId);
    }

    @Override
    public Oldman selectDescByOld(Oldman oldman) {
        return oldmanMapper.selectDescByOld(oldman);
    }

    @Override
    public List<Oldman> selectSelective(Oldman oldman) {
        return oldmanMapper.selectSelective(oldman);
    }

    /**
     * query oldman bed room building by oldman id
     *
     * @param oldmanId oldman id
     * @return
     */
    @Override
    public OldmanBedRoomBuildingVo queryOldmanBedRoomBuildingByOldmanId(Integer oldmanId) {

        return oldmanMapper.queryOldmanBedRoomBuildingByOldmanId(oldmanId);
    }

    /**
     * query oldman bed room building by bed id
     *
     * @param bedId
     * @return
     */
    @Override
    public OldmanBedRoomBuildingVo queryOldmanBedRoomBuildingByBedId(Integer bedId) {

        return oldmanMapper.queryOldmanBedRoomBuildingByBedId(bedId);
    }

    @Override
    public List<OldManVo> queryOldManBirthdayByDay(Map<String, Object> queryParam) {
        return oldmanMapper.queryOldManBirthdayByDay(queryParam);
    }

    @Override
    public List<OldManVo> queryOldManBirthdayByMonth(Map<String, Object> queryParam) {
        return oldmanMapper.queryOldManBirthdayByMonth(queryParam);
    }

    /**
     * 查询一周老人生日
     * @param queryParam
     * @return
     */
    @Override
    public List<OldManVo> selectByWeek(Map<String, Object> queryParam) {
        return oldmanMapper.selectByWeek(queryParam);
    }

    /**
     * 根据ID查询老人的信息及其额外信息
     * @param oldman
     * @return
     */
    @Override
    public OldManSupVo selectOldManSupByOld(Oldman oldman) {
        return oldmanMapper.selectOldManSupByOld(oldman);
    }

    /**
     * 老人及额外信息查询所有
     * @param queryParam
     * @return
     */
    @Override
    public List<OldManSupVo> showOldManSupAll(Map<String, Object> queryParam) {
        return oldmanMapper.showOldManSupAll(queryParam);
    }

    /**
     * 老人及额外信息查询所有（待评估，待缴费，已入院）
     * @param queryParam
     * @return
     */
    @Override
    public List<OldManSupVo> showOldManSupIn(Map<String, Object> queryParam) {
        return oldmanMapper.showOldManSupIn(queryParam);
    }

    @Override
    public List<CacOldManVo> showCacOldMan(OmcOldManDto omcOldManDto) {
        return oldmanMapper.showCacOldMan(omcOldManDto);
    }

    @Override
    public boolean queryIdCardRepet(Map<String, Object> queryMap) {
        int n = oldmanMapper.queryIdCardRepet(queryMap);
        if(n > 0){
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> oldmanCount(Long groupId) {

        Map<String,Object> data = new HashMap<>();

        List<Map<String,Object>> sexCount = oldmanMapper.countOldmanNumGroupBySex(groupId);
        List<Map<String,Object>> peopleTypeCount = oldmanMapper.countOldmanNumGroupByPeopleType(groupId);
        List<Map<String,Object>> ageCount = oldmanMapper.countOldmanNumGroupByAge(groupId);
        List<Map<String,Object>> servieTypeCount = oldmanMapper.countOldmanNumByServiceType(groupId);

        data.put("sexCount",sexCount);
        data.put("peopleTypeCount",peopleTypeCount);
        data.put("ageCount",ageCount);
        data.put("servieTyoeCount",servieTypeCount);

        return data;
    }

    @Override
    public QueryMachineOldInfoVo getOldmanInfoByOldmanId(Long oldmanId, LoginAuthDto loginAuthDto) {
        return oldmanMapper.getOldmanInfoByOldmanId(oldmanId);
    }

    @Override
    public PageInfo queryOldmanList(OldmanQueryDto oldmanQueryDto, LoginAuthDto loginAuthDto) {
        PageHelper.startPage(oldmanQueryDto.getPageNum(), oldmanQueryDto.getPageSize());
        oldmanQueryDto.setGroupId(loginAuthDto.getGroupId());
        List<QueryMachineOldmanVo> vos = oldmanMapper.queryOldmanList(oldmanQueryDto);
        return new PageInfo<>(vos);
    }

    @Override
    public Integer oldmanAppAddOldman(AppOldmanDto appOldmanDto, LoginAuthDto loginAuthDto) {

        //当前端传来的对象带身份证信息时
        if(appOldmanDto.getOldIdCard() != null && !appOldmanDto.getOldIdCard().equals("")) {

            Oldman oldman = checkOldmanExsitByIdCard(appOldmanDto.getOldIdCard());

            //如果系统中无该身份证，直接添加老人信息，并与用户绑定
            if (oldman == null) {
                //校验身份证
                if(!IdentityUtil.isIDCard(appOldmanDto.getOldIdCard())){
                    throw new OmcBizException(ErrorCodeEnum.OMC10060008);
                }
                if (appOldmanDto.getOldName() == null || appOldmanDto.getOldName().equals("")) {
                    throw new OmcBizException(ErrorCodeEnum.OMC10060007);
                }
                Oldman o = new Oldman();
                o.setHomeId(loginAuthDto.getGroupId().intValue());
                BeanUtils.copyProperties(appOldmanDto, o);
                //0-未入院 1-待评估 2-待缴费 3-已入院  4-已出院 5-试入住 6-去世 7-请假中 8-调房调级中 9-出院中 10-app用户
                o.setStatus(10);
                int ret = insertSelective(o);

                OmcAppUserOldmanBind appUserOldmanBind = new OmcAppUserOldmanBind();
                appUserOldmanBind.setOldmanId(o.getOldmanId().longValue());
                appUserOldmanBind.setUserId(loginAuthDto.getUserId());
                int save = omcAppUserOldmanBindService.save(appUserOldmanBind);
                /**
                 * 返回老人id
                 * 2021-12-20
                 */
                return o.getOldmanId();
            //如果有该身份证，将该老人id与用户绑定
            }else{
                //校验该老人是否被绑定过
                omcAppUserOldmanBindService.checkOldmanHasBound(oldman.getOldmanId().longValue(),loginAuthDto);

                //与用户绑定
                OmcAppUserOldmanBind appUserOldmanBind = new OmcAppUserOldmanBind();
                appUserOldmanBind.setOldmanId(oldman.getOldmanId().longValue());
                appUserOldmanBind.setUserId(loginAuthDto.getUserId());
                int save = omcAppUserOldmanBindService.save(appUserOldmanBind);
                /**
                 * 返回老人id
                 * 2021-12-20
                 */
                return oldman.getOldmanId();
            }
        //判断是否传入老人id，直接传入老人id，在【app用户与老人绑定表】中将数据插入
        }else if(appOldmanDto.getOldmanId() != null && appOldmanDto.getOldmanId() != 0){
                Oldman oldmanQuery = new Oldman();
                oldmanQuery.setOldmanId(appOldmanDto.getOldmanId().intValue());
                oldmanQuery = selectByOld(oldmanQuery);

                //校验老人是否存在
                if(oldmanQuery == null){
                    throw new OmcBizException(ErrorCodeEnum.OMC10038002);
                }

                //校验该老人是否已经绑定过
                omcAppUserOldmanBindService.checkOldmanHasBound(oldmanQuery.getOldmanId().longValue(),loginAuthDto);

                //绑定用户与老人
                OmcAppUserOldmanBind appUserOldmanBind = new OmcAppUserOldmanBind();
                appUserOldmanBind.setOldmanId(appOldmanDto.getOldmanId());
                appUserOldmanBind.setUserId(loginAuthDto.getUserId());
            int save = omcAppUserOldmanBindService.save(appUserOldmanBind);
            /**
             * 返回老人id
             * 2021-12-20
             */
            return appOldmanDto.getOldmanId().intValue();
        } else {
            //未填写身份证，直接添加老人信息，并与用户绑定
            Oldman o = new Oldman();
            if (appOldmanDto.getOldName() == null || appOldmanDto.getOldName().equals("")) {
                throw new OmcBizException(ErrorCodeEnum.OMC10060007);
            }
            BeanUtils.copyProperties(appOldmanDto, o);
            o.setHomeId(loginAuthDto.getGroupId().intValue());
            o.setStatus(10);
            int ret = insertSelective(o);

            OmcAppUserOldmanBind appUserOldmanBind = new OmcAppUserOldmanBind();
            appUserOldmanBind.setOldmanId(o.getOldmanId().longValue());
            appUserOldmanBind.setUserId(loginAuthDto.getUserId());
            int save = omcAppUserOldmanBindService.save(appUserOldmanBind);
            /**
             * 返回老人id By HD
             * 2021-12-20
             */
            return o.getOldmanId();
        }
    }

    @Override
    public List<OldManVo> queryBoundOldmanList(LoginAuthDto loginAuthDto) {

        OmcAppUserOldmanBind appUserOldmanBind = new OmcAppUserOldmanBind();
        appUserOldmanBind.setUserId(loginAuthDto.getUserId());
        List<OmcAppUserOldmanBind> appUserOldmanBindList = omcAppUserOldmanBindService.select(appUserOldmanBind);

        List<OldManVo> vos = new LinkedList<>();
        if(appUserOldmanBindList != null && appUserOldmanBindList.size() >0){
            List<Long> oldmanIdList = appUserOldmanBindList.stream().map( o -> o.getOldmanId()).collect(Collectors.toList());
            vos = oldmanMapper.queryOldmanListByIdList(oldmanIdList);
        }
        for(OldManVo vo : vos){
            if(vo.getRemark() != null && !vo.getRemark().equals("")){
                Oldman oldman = new Oldman();
                oldman.setOldmanId(Integer.parseInt(vo.getRemark()));
                oldman = selectByOld(oldman);
                if(oldman != null && oldman.getOldIdCard() != null){
                    vo.setOldIdCard(oldman.getOldIdCard());
                }
            }
        }
        return vos;
    }


    //根据身份证查询老人是否存在
    public Oldman checkOldmanExsitByIdCard(String idcard){
        Oldman oldman = new Oldman();
        oldman.setOldIdCard(idcard);
        return selectByOld(oldman);
    }


    @Override
    public Integer editAppOldmanInfo(AppOldmanDto appOldmanDto, LoginAuthDto loginAuthDto) {

        Oldman o = new Oldman();
        o.setOldmanId(appOldmanDto.getOldmanId().intValue());
        o = selectByOld(o);

        //检验该老人是否存在
        if(o == null){
            throw new OmcBizException(ErrorCodeEnum.OMC10031017,o.getOldmanId());
        }
        //校验是否是app用户
        if(o.getStatus() != 10){
            throw new OmcBizException(ErrorCodeEnum.OMC10060006);
        }
        BeanUtils.copyProperties(appOldmanDto,o);

        //校验修改后的身份证是否重复
        if(appOldmanDto.getOldIdCard() != null && !appOldmanDto.getOldIdCard().equals("")){

            if(!IdentityUtil.isIDCard(appOldmanDto.getOldIdCard())){
                throw new OmcBizException(ErrorCodeEnum.OMC10060008);
            }
            Oldman oldmanQuery = new Oldman();
            oldmanQuery.setOldIdCard(appOldmanDto.getOldIdCard());
            oldmanQuery = selectByOld(oldmanQuery);

            //不重复直接修改
            if(oldmanQuery == null){
                return updateByOldId(o);
            //重复后，不修改该老人身份证，将重复老人的id存入该老人的remark属性
            }else{
                //校验是否被app用户绑定过
                OmcAppUserOldmanBind obQuery = new OmcAppUserOldmanBind();
                obQuery.setOldmanId(oldmanQuery.getOldmanId().longValue());
                int hasBound = omcAppUserOldmanBindService.selectCount(obQuery);
                if(hasBound > 0){
                    throw new OmcBizException(ErrorCodeEnum.OMC10060005);
                }
                o.setOldIdCard(null);
                o.setRemark(oldmanQuery.getOldmanId().toString());
                return updateByOldId(o);
            }
        }
        return updateByOldId(o);
    }

    @Override
    public List<Integer> queryInOldmanIdList(Long groupId) {
        return oldmanMapper.queryInOldmanIdList(groupId);
    }

    /**
     * 老人出院专用
     *
     * 根据老人Id更新老人状态以及清除老人所在机构
     *
     * @param oldman
     *
     * @return
     */
    @Override
    public Integer checkOut(Oldman oldman) {

        return oldmanMapper.checkOut(oldman);
    }

    @Override
    public int updateByOldType(OmcOldManSupplement omcOldManSupplement) {





        //查询老人详情
        OmcOldManSupplement oldManSupplementQuery = new OmcOldManSupplement();
        oldManSupplementQuery.setOldManId(omcOldManSupplement.getOldManId());
        oldManSupplementQuery = omcOldManSupplementService.selectOne(oldManSupplementQuery);
        oldManSupplementQuery.setServiceType(omcOldManSupplement.getServiceType());

        if (PublicUtil.isNotEmpty(omcOldManSupplement.getLevelCareId())){
            OmcLevelCare omcLevelCare = levelCareService.selectByKey(omcOldManSupplement.getLevelCareId());
            oldManSupplementQuery.setLevelCareId(omcOldManSupplement.getLevelCareId());
            oldManSupplementQuery.setLevelCareName(omcLevelCare.getNursingCare());
        }


        //如果是入院老人  将老人状态改为待评估
        if(omcOldManSupplement.getServiceType() != null && omcOldManSupplement.getServiceType() == 2){
            //修改老人状态
            Oldman oldmanQuery = new Oldman();
            oldmanQuery.setOldmanId(omcOldManSupplement.getOldManId().intValue());
            oldmanQuery.setStatus(OldInConstant.DAIPINGGU);
        }

        //非入院老人清空暂存的床位id
        if(!omcOldManSupplement.getServiceType().equals(2)){
            oldManSupplementQuery.setBedId(null);
        }
        return omcOldManSupplementService.updateById(oldManSupplementQuery);
    }

    @Override
    public List<OldManTypeStatusVo> selectByOldType(Integer oldmanId) {
        return omcOldManSupplementMapper.selectByOldType(oldmanId);
    }

    @Override
    public List<Integer> queryCurTaskStates(LoginAuthDto loginAuthDto) {

        //定义老人状态码
        Set<Integer> statusSet = Sets.newHashSet();

        // 获取当前用户角色
        List<RpcRoleVo> roleVoList = uacRpcService.queryRoleListByUserId(loginAuthDto.getUserId());
        for (RpcRoleVo r : roleVoList) {
            String roleCode = r.getRoleCode();
            if (roleCode.equals(OldInConstant.IN_VAR_EVALUATE)) {
                //评估员 ===> 查看待评估老人列表
                statusSet.add(OldInConstant.DAIPINGGU);
            }
            if (roleCode.equals(OldInConstant.IN_VAR_RECETION_MINISTER)) {
                // 服务部长 ===》 查询已评估老人列表
                statusSet.add(OldInConstant.YIPINGGU);
            }
            if (roleCode.equals(OldInConstant.IN_VAR_RECETIONIST)) {
                // 接待员角色 ===> 查询已评估老人列表
                statusSet.add(OldInConstant.YIPINGGU);
            }
            if (roleCode.equals(OldInConstant.IN_VAR_HOME)){
                // 院长 == 》 查询缴费待审批
                statusSet.add(OldInConstant.DAISHENPI);
            }
            if (roleCode.equals(OldInConstant.IN_VAR_CHARGE)){
                // 收费员 ===》 待缴费老人列表
                statusSet.add(OldInConstant.DAIJIAOFEI);
            }
        }

        List<Integer> statusList = new LinkedList<>(statusSet);
        return statusList;
    }

    @Override
    public Integer updateOldmanByEvaluate(CacOldmanDto cacOldmanDto) {
        //老人额外信息
        OmcOldManSupplement oldManSupplementQuery = new OmcOldManSupplement();
        oldManSupplementQuery.setOldManId(cacOldmanDto.getOldmanId());
        oldManSupplementQuery = omcOldManSupplementService.selectOne(oldManSupplementQuery);

        //根据评估更新老人自理等级
        OmcLevelCare omcLevelCare = levelCareService.selectByKey(cacOldmanDto.getLevelCareId());
        oldManSupplementQuery.setLevelCareId(cacOldmanDto.getLevelCareId());
        oldManSupplementQuery.setLevelCareName(omcLevelCare.getNursingCare());

        //如果是添加了初次评估 修改老人状态
        if(cacOldmanDto.getCacType() == null || cacOldmanDto.getCacType() == 1){

            Oldman oldman = new Oldman();
            oldman.setOldmanId(cacOldmanDto.getOldmanId().intValue());
            oldman = selectByOld(oldman);
            oldman.setStatus(cacOldmanDto.getStatus());
            int retStatus = updateByOldId(oldman);
        }

        int ret = omcOldManSupplementService.update(oldManSupplementQuery);

        return ret;
    }

    @Override
    public List<OldmanInVo> queryOldmanInCurTaskList(OldmanInQueryDto queryDto) {
        return oldmanMapper.queryOldmanInCurTaskList(queryDto);
    }

    @Override
    public List<OldmanInVo> queryNeedDailyEvaluateOldmanList(List<Integer> oldmanIdList) {
        return oldmanMapper.queryNeedDailyEvaluateOldmanList(oldmanIdList);
    }

    /**
     * 查询老人列表
     *
     * @param oldmanInQueryDto
     * @return
     */
    @Override
    public List<OldmanRpcVo> queryOldmanByGroupIdAndStatusList(OldmanInQueryDto oldmanInQueryDto) {

        return oldmanMapper.queryOldmanByGroupIdAndStatusList(oldmanInQueryDto);
    }

    @Override
    public OldmanExceptionVo queryOldmanException(Long oldmanId, LoginAuthDto loginAuthDto) {

        //创建返回对象
        OldmanExceptionVo oldmanExceptionVo = new OldmanExceptionVo();

        //创建查询的起止时间
        String endDate = DateUtil.getDate_dtShort();
        endDate = DateUtil.getTomorrow(endDate);
        String beginDate = DateUtil.getThirty();

        //创建报警查询对象
        DeviceAlertReqVo deviceAlertReqVo = new DeviceAlertReqVo();
        deviceAlertReqVo.setOldmanIdList(Lists.newArrayList(oldmanId.intValue()));
        deviceAlertReqVo.setStartTime(beginDate);
        deviceAlertReqVo.setEndTime(endDate);
        List<DeviceAlertReqVo> deviceAlertReqVoList = dmcRpcService.queryDeviceAlertByOldIdAndDate(deviceAlertReqVo);

        //查询饮食异常
        Example example = new Example(OmcNursingLog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("groupId",loginAuthDto.getGroupId());
        criteria.andLessThanOrEqualTo("date",endDate);
        criteria.andGreaterThanOrEqualTo("date",beginDate);
        List<OmcNursingLog> nursingLogList = nursingLogService.selectByExample(example);

        //创建老人异常饮食对象集合
        List<OldmanMealExceptionVo> oldmanMealExceptionList = Lists.newArrayList();

        //循环取值
        nursingLogList.stream().forEach(n->{
            if(n.getMeal() != null && !n.getMeal().equals("")){
                //获取膳食记录字符串
                String allMeal = n.getMeal();
                //分隔
                String meals[] =allMeal.split("μ");

                for(int i=0;i<=meals.length-1;i++){
                    //分隔
                    String str[] = meals[i].split("ν");
                    //分隔老人信息
                    String oldMans[] = str[1].split("-");
                    //获取老人id集合，默认插入的是0，如果是0则代表没有数据
                    if (!(str[1].equals("0"))) {
                        for (int k = 0; k <= oldMans.length - 1; k++) {
                            /*
                             * 2019-11-21
                             * 结构修改为:
                             * oldmans[k] : 老人id:老人姓名
                             * */
                            String[] oldmanIdAndOldmanName = oldMans[k].split(":");
                            Integer oldmanIdOfMeal = Integer.valueOf(oldmanIdAndOldmanName[0]);
                            if(oldmanIdOfMeal.toString().equals(oldmanId.toString())){
                                //创建老人异常饮食对象
                                OldmanMealExceptionVo oldmanMealExceptionVo = new OldmanMealExceptionVo();
                                //放入用餐类型
                                oldmanMealExceptionVo.setMealType(Integer.valueOf(str[0]));
                                //放入老人id
                                oldmanMealExceptionVo.setOldmanId(oldmanIdOfMeal.longValue());
                                //放入老人姓名
                                oldmanMealExceptionVo.setOldName(oldmanIdAndOldmanName[1]);
                                //放入异常日期
                                oldmanMealExceptionVo.setDate(n.getDate());
                                //获取特殊情况，默认插入的是0，如果是0则代表没有数据
                                if (!(str[2].equals("0"))) {
                                    oldmanMealExceptionVo.setRemark(str[2]);
                                }
                                oldmanMealExceptionList.add(oldmanMealExceptionVo);
                            }
                        }
                    }
                }
            }
        });

        //查询用药异常
        List<MedicRecordVo> medicExceptionList = omcMedicRecordService.queryOldmanMedicException(oldmanId,beginDate,endDate);

        //填充数据
        oldmanExceptionVo.setDeviceAlertReqVoList(deviceAlertReqVoList);
        oldmanExceptionVo.setMedicExceptionList(medicExceptionList);
        oldmanExceptionVo.setOldmanMealExceptionList(oldmanMealExceptionList);

        return oldmanExceptionVo;
    }

    /**
     * query oldman bed room building vo by room no and bed no
     *
     * @param roomNo the room no
     * @param bedNo  the bed no
     *
     * @return the oldman bed room building vo
     */
    @Override
    public OldmanBedRoomBuildingVo queryOldmanBedRoomBuildingByRoomNoAndBedNo(String roomNo, String bedNo) {

        return oldmanMapper.queryOldmanBedRoomBuildingByRoomNoAndBedNo(roomNo, bedNo);
    }

    @Override
    public List<Oldman> selectByNo(Oldman oldman){
        return oldmanMapper.selectByNo(oldman);
    }

    @Override
    public List<OldmanArchivesListVo> selectQueryOldman(OldmanArchivesQueryDto oldmanArchivesQueryDto) {
        return oldmanMapper.selectQueryOldman(oldmanArchivesQueryDto);
    }

    @Override
    public Oldman select(Oldman old) {
        return oldmanMapper.select(old);
    }

    @Override
    public PageInfo listPage(com.csun.cmny.provider.model.dto.OldmanQueryDto oldmanQueryDto, LoginAuthDto loginAuthDto) {

        if(PublicUtil.isEmpty(oldmanQueryDto.getGroupId()) ){
            oldmanQueryDto.setGroupId(loginAuthDto.getGroupId());
        }
        PageHelper.startPage(oldmanQueryDto.getPageNum(), oldmanQueryDto.getPageSize());
        List<OldManSupVo> oldManSupVos = oldmanMapper.listPage(oldmanQueryDto);

        return new PageInfo<>(oldManSupVos);
    }

    @Override
    public List<OldManSupVo> selectOldManByExcel(OldManSelectDto oldManSelectDto) {
        return oldmanMapper.selectOldManByExcel(oldManSelectDto);
    }

    /*
     * 大数据平台注册用户占比查询
     * */
    @Override
    public List<PercentVo> selectByGroup(Long groupId) {

        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryChildListByGroupId(groupId);
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }

        RegisterVo registerVo = oldmanMapper.selectByGroup(groupIdList);

        DecimalFormat df = new DecimalFormat("0.00%");
        List<PercentVo> percentVos = new ArrayList<>();
        PercentVo percentVo = new PercentVo("注册总人数",registerVo.getCount(),
                null);
        percentVos.add(percentVo);
        percentVo = new PercentVo("男性",registerVo.getMan(),
                df.format(registerVo.getMan().doubleValue()/registerVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("女性",registerVo.getWomen(),
                df.format(registerVo.getWomen().doubleValue()/registerVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("60岁以下",registerVo.getOverSixty(),
                df.format(registerVo.getOverSixty().doubleValue()/registerVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("60-70岁",registerVo.getSixToSeventy(),
                df.format(registerVo.getSixToSeventy().doubleValue()/registerVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("70-80岁",registerVo.getSeventyToEighty(),
                df.format(registerVo.getSeventyToEighty().doubleValue()/registerVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("80-90岁",registerVo.getEightyToNinety(),
                df.format(registerVo.getEightyToNinety().doubleValue()/registerVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("90岁以上",registerVo.getEightyToNinety(),
                df.format(registerVo.getOverNighty().doubleValue()/registerVo.getCount()));
        percentVos.add(percentVo);
        return percentVos;
    }
    /*
     * 大数据平台健康占比亚健康展示
     * */
    @Override
    public List<PercentVo> selectByHealth(Long groupId) {

        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryChildListByGroupId(groupId);
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }

        HealthVo healthVo = oldmanMapper.selectByHealth(groupIdList);

        DecimalFormat df = new DecimalFormat("0.00%");
        List<PercentVo> percentVos = new ArrayList<>();
        PercentVo percentVo = new PercentVo("代谢类",healthVo.getMetabolic(),
                df.format(healthVo.getMetabolic().doubleValue()/healthVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("心脑血管类",healthVo.getBloodVessels(),
                df.format(healthVo.getBloodVessels().doubleValue()/healthVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("骨关节类",healthVo.getJoint(),
                df.format(healthVo.getJoint().doubleValue()/healthVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("消化系统类",healthVo.getDigestive(),
                df.format(healthVo.getDigestive().doubleValue()/healthVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("呼吸系统类",healthVo.getBreath(),
                df.format(healthVo.getBreath().doubleValue()/healthVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("其他",healthVo.getOther(),
                df.format(healthVo.getOther().doubleValue()/healthVo.getCount()));
        percentVos.add(percentVo);
        percentVo = new PercentVo("健康",healthVo.getHealth(),
                df.format(healthVo.getHealth().doubleValue()/healthVo.getCount()));
        percentVos.add(percentVo);
        return percentVos;
    }
    /*
     * 大数据平台居家养老服务展示
     * */
    @Override
    public List<PercentVo> selectByService(Long groupId) {

        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryChildListByGroupId(groupId);
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }

        //机构下查询服务名
       List<GroupServiceVo> groupServiceVos = oldmanMapper.selectServiceByPid(groupIdList);

        //查询居家签约老人总数
       ServiceOrderVo serviceOrderVo = oldmanMapper.selectOldmanInHome(groupIdList);

        //查询服务工单总数以及服务项目占比
        Map<String,Number> countVos = oldmanMapper.selectByService(groupServiceVos, groupIdList);
        /*if(serviceOrderVo != null){
            serviceOrderVo.setServiceOrder(countVos);
        }*/
        List<PercentVo> percentVos = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00%");
        PercentVo percentVo = new PercentVo();
        percentVo = new PercentVo("签约老人总数",serviceOrderVo.getHome(),null);
        percentVos.add(percentVo);
        Integer counts = countVos.get("工单数").intValue();
        percentVo = new PercentVo("服务工单总数", counts,null);
        percentVos.add(percentVo);
        countVos.remove("工单数");
        for (String s:countVos.keySet()) {
            percentVo = new PercentVo(s, countVos.get(s).intValue(),df.format(countVos.get(s).doubleValue()/counts));
            percentVos.add(percentVo);
        }
        return percentVos;
    }
    /*
     * 大数据平台居家养老服务展示
     * */
    @Override
    public List<OlderNumVo> selectOldmanByNurseHome(OlderNumVo olderNumVo) {

        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(olderNumVo.getGroupId());
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }
        List<OlderNumVo> olderNumVos = oldmanMapper.selectOldmanByNurseHome(olderNumVo.getYear(),groupIdList);
        for (OlderNumVo o:olderNumVos) {
            for (GroupVo g:groupVoList) {
                if(o.getGroupId().equals(g.getId())){
                    o.setGroupName(g.getGroupName());
                }
            }
        }
        return olderNumVos;
    }
    /*
     * 大数据平台居家养老服务展示-居家服务数据
     * */
    @Override
    public List<ServiceOrderVo> selectServiceByNurseHome(Long groupId) {

        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(groupId);
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }

        //机构下查询服务名
        List<GroupServiceVo> groupServiceVos = oldmanMapper.selectServiceByPid(groupIdList);

        //查询服务工单总数以及服务项目占比
        List<Map<String,Number>> countVos = oldmanMapper.selectServiceByNurseHome(groupServiceVos,groupId,groupIdList);
        List<ServiceOrderVo> serviceOrderVos = new ArrayList<>();
        List<PercentVo> percentVos = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00%");
        PercentVo percentVo = new PercentVo();
        for (Map<String,Number> map:countVos) {
            ServiceOrderVo serviceOrderVo = new ServiceOrderVo();
            serviceOrderVo.setGroupId((Long) map.get("group_id"));
            map.remove("group_id");
            map.remove("group_name");
            Integer count = map.get("总服务次数").intValue();
            map.remove("总服务次数");
            for (GroupVo g:groupVoList) {
                if(g.getId().equals(map.get("group_id"))){
                    serviceOrderVo.setGroupName(map.get("group_name")+"");
                }
            }
            for (String s: map.keySet()) {
                percentVo = new PercentVo(s,map.get(s).intValue(),df.format(map.get(s).doubleValue()/count));
                percentVos.add(percentVo);
            }
            serviceOrderVo.setPercentVos(percentVos);
            serviceOrderVos.add(serviceOrderVo);
        }
        return serviceOrderVos;
    }
    /*
     * 大数据平台居家养老服务展示-居家服务数据
     * */
    @Override
    public List<ServiceOrderVO> selectOrderByNurseHome(ServiceOrderVO serviceOrderVO) {
        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(serviceOrderVO.getGroupId());
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }
        return omcServiceOrderMapper.selectOrderByNurseHome(serviceOrderVO,groupIdList);
    }
    /*
     * 集团化查询老人信息
     * */
    @Override
    public List<OldManSupVo> selectAllOldman(OldManSupVo oldManSupVo) {
        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(oldManSupVo.getHomeId().longValue());
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }
        List<OldManSupVo> oldManSupVos = oldmanMapper.selectAllOldman(oldManSupVo,groupIdList);
        for (OldManSupVo o:oldManSupVos) {
            for (GroupVo g:groupVoList) {
                if(g.getId().equals(o.getHomeId().longValue())){
                    o.setGroupName(g.getGroupName());
                }
            }
        }
        return oldManSupVos;
    }
    /*
     * 老人咨询查询
     * */
    @Override
    public List<OldmanAdvisoryVo> selectAdvisory(OldmanAdvisoryVo oldmanAdvisoryVo) {
        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(oldmanAdvisoryVo.getGroupId());
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }
        oldmanAdvisoryVo.setGroupId(null);
        List<OldmanAdvisoryVo> oldmanAdvisoryVos = oldmanMapper.selectAdvisory(oldmanAdvisoryVo, groupIdList);
        for (OldmanAdvisoryVo o:oldmanAdvisoryVos) {
            for (GroupVo g:groupVoList) {
                if(o.getGroupId().equals(g.getId())){
                    o.setGroupName(g.getGroupName());
                }
            }
        }
        return oldmanAdvisoryVos;
    }
    /**
     * 查询首页老人分类占比
     * @return Wrapper
     * @author HD
     * @date 2021/11/26 13:54
     */
    @Override
    public OldmanIndexVo selectOldmanIndex(Long groupId) {
        return oldmanMapper.selectOldmanIndex(groupId);
    }
}
